# encoding:utf-8
# 调用产线接口增加 euc 及版本号信息
# author yeyi

import openpyxl
import requests
import traceback
import json
import time


# 联调
#url = "http://10.2.3.17:8080/v1/bss/vehicle/ecu/entry"
# 预发布
#url = "http://10.123.2.99:8080/v1/bss/vehicle/ecu/entry"
# 生产
#url = "http://10.123.16.15:8080/v1/bss/vehicle/ecu/entry"
url = "http://10.123.16.111:8080/v1/bss/vehicle/ecu/entry"

headers = {
    'Content-Type': "application/json"
}

# 每次请求多少个 vin 的数据
offset = 1
# 发送时间
sendTimeStr = "2021-06-11 10:47:01"

# 打开excel文件,获取工作簿对象
wb = openpyxl.load_workbook("./ExportECU.xlsx")

# 获取workbook中所有的表格
sheets = wb.sheetnames

def printt(s):
    #print(s)
    # 建立临时输出文件
    f = open("ExportECU.log", "a+", encoding="utf-8")  # 打开文件以便写入
    print(s,file=f)
    f.close()



# 构造每个 vin 单位的请求 body
# isAdd: true为插入  false为更新
def makeBodySingleVin(ws, i, isAdd):
    vin = ws.cell(row=i, column=3).value
    if vin is None or len(vin)==0:
      printt('makeBodySingleVi vin empty')
      return None
    tboxEucName = "TBOX"
    tboxPartNum = ws.cell(row=i, column=5).value
    tboxSwVersion = ws.cell(row=i, column=6).value
    tboxHwVersion = ws.cell(row=i, column=7).value
    acuEucName = "ACU"
    acuPartNum = ws.cell(row=i, column=8).value
    acuSwVersion = ws.cell(row=i, column=9).value
    acuHwVersion = ws.cell(row=i, column=10).value
    dmsName = "DMS"
    dmsPartNum = ws.cell(row=i, column=11).value
    dmsSwVersion = ws.cell(row=i, column=12).value
    dmsHwVersion = ws.cell(row=i, column=13).value
    acurEucName = "ACUR"
    acurPartNum = ws.cell(row=i, column=14).value
    acurSwVersion = ws.cell(row=i, column=15).value
    acurHwVersion = ws.cell(row=i, column=16).value
    printt("makeBodySingleVi vin: "+vin)
    body = "{\"dataTime\":\""+sendTimeStr+"\",\"ecus\":[{"
    body = body + "\"ecuName\": \""    + tboxEucName + "\","
    body = body + "\"partNumber\": \"" + tboxPartNum + "\","
    body = body + "\"hwVersion\": \"" + tboxHwVersion + "\","
    body = body + "\"swVersion\": \""  + tboxSwVersion + "\"},{"

    body = body + "\"ecuName\": \""    + acuEucName + "\","
    body = body + "\"partNumber\": \"" + acuPartNum + "\","
    body = body + "\"hwVersion\": \"" + acuHwVersion + "\","
    body = body + "\"swVersion\": \""  + acuSwVersion + "\"}"

    if (dmsPartNum is not None) and len(dmsPartNum) > 5:
        body = body + ",{"
        body = body + "\"ecuName\": \""    + dmsName + "\","
        body = body + "\"partNumber\": \"" + dmsPartNum + "\","
        body = body + "\"hwVersion\": \"" + dmsHwVersion + "\","
        body = body + "\"swVersion\": \""  + dmsSwVersion + "\"}"

    if (acurPartNum is not None) and len(acurPartNum) > 5:
        body = body + ",{"
        body = body + "\"ecuName\": \""    + acurEucName + "\","
        body = body + "\"partNumber\": \"" + acurPartNum + "\","
        body = body + "\"hwVersion\": \"" + acurHwVersion + "\","
        body = body + "\"swVersion\": \""  + acurSwVersion + "\"}"

    if isAdd:
      body = body + "],\"status\":0,\"vin\":\""
    else:
      body = body + "],\"status\":1,\"vin\":\""  

    body = body + vin + "\"}"
    printt(body)
    return body

# 构造请求 body
# isAdd: true为插入  false为更新
def makeBody(ws, i, isAdd):
    try:
        body = "{\"datas\":["
        max = ws.max_row if i+offset > ws.max_row else i+offset
        lineMax = 0
        for j in range(i, max):
            lineMax = j
            js = makeBodySingleVin(ws, j, isAdd)
            if js is not None:
              body = body + js
              if j < max:
                  body = body + ","

        typ = "0"
        if not isAdd:
          typ = "1"
          # 删除多余的逗号
        if body.endswith(","):
          body =  body[:-1]
        body = body + "],\"sendTime\":\""+sendTimeStr + \
            "\",\"token\":\"oK9+ZtZyVfYKkQpKM+FNGNkYADeTznBK9q+4dCdBM9U=\",\"type\":\""+ typ +"\"}"
        printt("makeBody j:"+str(lineMax))
        printt(body)
        return body
    except:
        # 打印错误信息
        printt("makeBody err: ")
        traceback.print_exc()
        return ""

# 返回接口返回数据,失败返回 None
def fun(ws, i, isAdd):
    body = makeBody(ws, i, isAdd)
    try:
        response = requests.request(
            "POST", url, data=body.encode('utf-8'), headers=headers)
    except:
        # 打印错误信息
        printt("Exception: "+str(i))
        traceback.print_exc()
        return None

    jsStr = str(response.content, 'utf-8')
    # printt(jsStr)
    return json.loads(jsStr)

printt(sheets)
printt(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
for sheet in sheets:
    if sheet != "AM8OTA软硬件明细":
        continue

    ws = wb[sheet]
    for i in range(2, ws.max_row + 1, offset):
        vin = ws.cell(row=i, column=4).value
        printt("out i: "+str(i)+", vin: "+str(vin))
        if vin is None:
            continue
        
        js = fun(ws, i, True)
        if js is None:
          continue

        if 'errorCode' not in js:
            printt("errorCode not exist "+str(i))
            continue

        errorCode = js['errorCode']
        if "000"==errorCode:
          continue

        printt("errorCode "+str(i)+": "+str(js))
        errorMessage = js['errorMessage']
        if "车辆ECU信息已存在" not in errorMessage:
          continue

        js = fun(ws, i, False)
        if js is None:
          continue

        errorCode = js['errorCode']
        if "000"==errorCode:
          continue

        errorMessage = js['errorMessage']
        printt("errorCode2 "+str(i)+": "+str(js))